package com.kepler.social.web.comp;

import com.kepler.social.common.constants.Enums;
import com.kepler.social.domain.user.security.UserSecurityAggregate;
import com.kepler.social.domain.user.security.UserSecurityRepository;
import com.kepler.social.service.vo.MobilePhoneVo;
import com.kepler.social.service.vo.SysUserVo;
import com.kepler.social.web.authentication.MobileAuthenticationToken;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class MobileAuthenticationProvider extends BaseAuthenticationProvider implements AuthenticationProvider {
    @Resource
    private UserSecurityRepository userSecurityRepository;
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        MobileAuthenticationToken mobileAuthenticationToken = (MobileAuthenticationToken)authentication;
        MobilePhoneVo phoneVo = (MobilePhoneVo)mobileAuthenticationToken.getPrincipal();
        SysUserVo sysUser = new SysUserVo();
        try{
            UserSecurityAggregate aggregate = userSecurityRepository.findByMobilePhone(phoneVo.getCountryCallingCode(),
                    phoneVo.getMobilePhoneNumber());
            aggregate.checkMobilePhoneInUse();
            sysUser.setId(aggregate.getRoot().getUserId());
            sysUser.setLoginMethod(Enums.LoginMethodEnum.MOBILE_PHONE.code);
        }catch (IllegalArgumentException e){
            throw new UsernameNotFoundException(e.getMessage());
        }catch (Exception e){
            log.error("findUserId mobilePhoneNumber {} err {}", phoneVo.getMobilePhoneNumber(), e, e);
            throw new UsernameNotFoundException("系统错误，请联系管理员");
        }
        UserDetails user = getUserDetails(sysUser);
        return new MobileAuthenticationToken(user, user.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        //确保authentication能转成该类
        return authentication.equals(MobileAuthenticationToken.class);
    }
}